import os

from django.shortcuts import render,reverse
from django.http import HttpResponse,JsonResponse
from django.db.models import Q
from django.core.paginator import Paginator

from .. import models
from .ClassifyViews import select_all_classify
from .UsersViews import uploadfile


# 后台 - 图书商品管理


# 图书商品管理 - 列表
def bookindex(request):
    # 获取图书数据
    data = models.Books.objects.all()

    # 搜索功能
    # 接收搜索条件
    selecttype = request.GET.get('selecttype',None)
    keywords = request.GET.get('keywords',None)
    # 有条件搜索
    if selecttype:
        # 根据书名/作者进行搜索，导入Q模块
        if selecttype == 'all':
            data = data.filter(
                    Q(title__contains=keywords)
                    |Q(author__contains=keywords)
                    )
        else:
            search = {f'{selecttype}__contains':keywords}
            data = data.filter(**search)

    # 分页功能
    # 导入Paginator模块，实例化分页对象
    p = Paginator(data,20)
    # 获取当前页
    page_index = request.GET.get('page',1)
    # 根据页码数获取当前页的数据
    data = p.page(page_index)


    # 分配数据
    context = {'data':data}

    # 加载模板
    return render(request,'myadmin/books/index.html',context)


# 图书商品管理 - 添加
def bookadd(request):
    if request.method == 'GET':
        # 获取分类数据，并加载模板
        context = {'classifydata': select_all_classify()}
        return render(request,'myadmin/books/add.html',context)
    else:
        # 接收表单数据
        data = request.POST.dict()
        data.pop('csrfmiddlewaretoken')

        # 检测是否有封面图上传
        if not request.FILES.get('imgfile',None) :
            return HttpResponse('<script>alert("需要上传至少一张封面图");history.go(-1);</script>')

        # 添加图书对象
        try:
            data['classifyid'] = models.BookType.objects.get(id=data['classifyid'])
            bookobj = models.Books(**data)
            bookobj.save()
        except:
            return HttpResponse('<script>alert("图书添加失败");history.back();</script>')

        # 上传封面图
        try:
            imgobj = models.BookImgs()
            imgobj.bookid = bookobj
            imgobj.img_url = uploadfile(request,'imgfile')
            imgobj.save()
        except:
            bookobj.delete()
            return HttpResponse('<script>alert("封面图上传失败");history.back();</script>')

        url = reverse('myadmin_bookindex')
        return HttpResponse(f'<script>alert("图书添加成功");location.href="{url}"</script>')



# 图书商品管理 - 删除
def bookdelete(request):
    # 接收被删除图书的id
    id = request.GET.get('id')

    # 获取图书对象
    bookobj = models.Books.objects.get(id=id)

    # 判断图书是否已经出售

    # 获取所有封面图的url，并删除封面图
    try:
        for i in bookobj.bookimgs_set.all():
            os.remove('.' + i.img_url)
    except:
        return JsonResponse({f'error':1,'msg':'封面图删除失败:{i.img_url}'})

    # 删除图书对象
    try:
        bookobj.delete()
        return JsonResponse({'error':0,'msg':'删除成功'})
    except:
        return JsonResponse({'error':2,'msg':'图书删除失败'})


# 图书商品管理 - 修改
def bookedit(request,bid):
    #
    if request.method == 'GET':
        bookobj = models.Books.objects.get(id=bid)
        for i in bookobj.bookimgs_set.all() :
            bookimg = i.img_url
        context = {'bookobj':bookobj,'classifydata':select_all_classify(),'bookimg':bookimg}
        return render(request,'myadmin/books/edit.html',context)
    else:
        # 接收编辑后的表单数据
        data = request.POST.dict()
        data.pop('csrfmiddlewaretoken')
        data.pop('imgfile')
        # 更新数据
        models.Books.objects.filter(id=bid).update(**data)
        url = reverse('myadmin_bookindex')
        return HttpResponse(f'<script>alert("编辑成功");location.href="{url}"</script>')





